const pool = require("../base/mysql").pool,
    moment = require('moment'),
    fs = require("fs"),
    staticPath = require('../config-local').staticPath,
    userService = require('../user/userService');

const sql_updateProject_tmp = "UPDATE `project_storage` SET `userId` = ? where userId=?;",
    sql_createProject = "INSERT INTO `project_storage`(`name`,`createTime`,`updateTime`,`blockCount`,`content`,`projectType`,`userId`)VALUES(?,?,?,?,?,?,?);",
    sql_updateProjById = "UPDATE `project_storage` SET `name` = ?, `updateTime` = ?, `blockCount` = ?, `content` = ?  WHERE `id` = ? and userId=?;",
    sql_updateVisitNum = "UPDATE `project_storage` SET `visited` = `visited`+1 WHERE `id` = ? and userId=?;",
    sql_removeProjById = "DELETE FROM `project_storage` WHERE id=? and userId=?;",
    sql_projectInfos = "SELECT `id`,`name`,UNIX_TIMESTAMP(`createTime`) as createTime,UNIX_TIMESTAMP(`updateTime`) as updateTime,`blockCount`,`visited`,LENGTH(`content`) as length FROM `project_storage` where userId=?;",
    sql_projectInfosByPage = "SELECT `id`,`name`,`projectType`,UNIX_TIMESTAMP(`updateTime`) as updateTime FROM `project_storage` where userId=? order by updateTime desc limit ?,?;",
    sql_projectCount = "SELECT count(`id`) as count FROM `project_storage` where userId=?;",
    sql_juheShareProjectCount = "SELECT count(distinct(`projId`)) as count FROM `juhe_project_share` where userId=?;",
    sql_juheShareHistoryProjectCount = "SELECT count(id) as count FROM `juhe_project_share` where userId=? and projId=?;",
    sql_juheShareAdaptProjectCount = "SELECT count(id) as count FROM `juhe_project_share` where userId=? and fromShareId=?;",
    sql_getMaxShareId = "select max(id) as maxId from juhe_project_share where userId=? and projId=?",
    sql_hasProject = "SELECT count(`id`) as count FROM `project_storage` where id=? and userId=?;",
    sql_insertContestTemplete = "insert into contest_records(contestId,userId,projId) values(?,?,?)",
    sql_getProjTemplete = "select * from project_templete",
    sql_judgeContestRecord = "select * from contest_records where contestId=? and userId=?",
    sql_updateContestRecordPublishFlag = "update contest_records set publishFlag=1 where  userId=? and projId=?",
    sql_getProjById = "SELECT `name`,`content` FROM `project_storage` where userId=? and id=? limit 1;",
    sql_getUserProjByPid = "SELECT `content` FROM `project_storage` where id=? limit 1;",
    sql_hasProject_share = "SELECT count(`projId`) as count FROM `juhe_project_share` where userId=? and projId=?;",
    // sql_juheShareProj_create = "insert into `juhe_project_share`(`userId`,`projId`,`name`,`content`) select userId,id as projId,name,content from project_storage where userId=? and id=?;",
    sql_juheShareProj_create = "INSERT INTO `juhe_project_share`(`userId`,`projId`,`name`,`content`) VALUES(?,?,?,?);",
    sql_groupShare_create = "INSERT INTO `juhe_group_share`(`userId`,`name`,`content`) VALUES(?,?,?);",
    sql_shareProj_update = "UPDATE `juhe_project_share` SET `name` = ?,`content` = ? WHERE userId=? and `id` = ?;", //更新源文件
    sql_cancleShareProj = "DELETE from `juhe_project_share` WHERE `userId` = ? AND `projId` = ?;",
    sql_updatejuheSharedById = "update juhe_project_share set fromShareId=? where userId=? and id=?",
    sql_viewShareProjByPid = "select `content` from `juhe_project_share` WHERE `id` = ?;",
    sql_viewJuheGroupShareProjByPid = "select `content` from `juhe_group_share` WHERE `id` = ?;", //查看聚合小组分享
    // sql_getJuheShareProListjByPage = "SELECT `id`,`name`,UNIX_TIMESTAMP(`createTime`) as createTime FROM `juhe_project_share` where userId=? order by createTime limit ?,?;";
    sql_getJuheShareProListjByPage = "SELECT m1.* FROM  juhe_project_share m1 LEFT JOIN juhe_project_share m2 ON (m2.userId=? and m1.projId = m2.projId AND m1.id < m2.id) WHERE m1.userId=? and m2.id IS NULL order by createTime desc LIMIT ?,?",
    sql_getJuheShareHistoryProjListByPage = "select `id`,`name`,UNIX_TIMESTAMP(`createTime`) as createTime from juhe_project_share where userId=? and projId=? order by createTime desc",
    sql_getJuheShareAdaptListByPage = "select `id`,`name`,UNIX_TIMESTAMP(`createTime`) as createTime from juhe_project_share where userId=? and fromShareId=?  order by createTime desc";
//============================================//
//更新旧用户信息 临时接口
const updateProject_tmp = (userInfo) => {
    var oldUserId = userInfo.oldUserId,
        userId = userInfo.id,
        args = [userId, oldUserId];
    pool.query(sql_updateProject_tmp, args, (err, result) => {
        if (err) {
            console.error(err);
        }
    });
};

//判断科技日报用户参赛纪录
const judgeContestRecord = (contestId, userId, cb) => {
    var ret = {
        result: -1,
        msg: "报名失败"
    },
        args = [contestId, userId];
    pool.query(sql_judgeContestRecord, args, (err, rows) => {
        if (err) {
            console.error(err);
        } else if (rows.length === 0) {
            ret = {
                result: 1
            };
        } else if (rows.length > 0) {
            ret = {
                result: 0,
                projId: rows[0].projId,
                publishFlag: rows[0].publishFlag
            };
        }
        cb(ret);
    });
};
//更新科技日报参赛记录
const updateContestRecordPublishFlag = (userId, projId) => {
    var args = [userId, projId];
    pool.query(sql_updateContestRecordPublishFlag, args, (err) => {
        if (err) {
            console.error(err);
        }
    });
};

//给科技日报报名用户生成参赛模板
const addProjTemplete = (contestId, userId, cb) => {
    var ret = {
        result: -1,
        msg: "报名失败"
    };
    judgeContestRecord(contestId, userId, (list) => {
        if (list.result === 0) {
            if (list.publishFlag === 1) { //已经发布过的
                ret = {
                    result: -1,
                    msg: "已经报名完毕,不可重复参赛"
                }
            } else {
                ret = {
                    result: 0,
                    projId: list.projId,
                    projectType: "kjrb_contest"
                }
            }
            cb(ret);
        } else if (list.result === 1) {
            pool.query(sql_getProjTemplete, (err, rows) => {
                if (err) {
                    console.error(err);
                    cb(ret);
                    return;
                }
                var project = JSON.parse(rows[0].content),
                    projectType = "kjrb_contest",
                    thumbnail = rows[0].thumbnail;
                createProject(userId, project, projectType, thumbnail, (rb) => {
                    if (rb.result == 0) {
                        ret = rb;
                        var projId = rb.projId,
                            args = [contestId, userId, projId];
                        pool.query(sql_insertContestTemplete, args, (err) => {
                            if (err) {
                                console.error(err);
                            }
                            cb(ret);
                        });
                    } else {
                        console.error(err);
                        cb(ret);
                    }
                });
            });
        } else {
            cb(ret);
        }
    })
};

//创建工程
const createProject = (userId, project, projectType, thumbnail, cb) => {
    let ret, projectName = project.projectName ? project.projectName : "新项目",
        createTime = moment().format('YYYY-MM-DD HH:mm:ss'),
        blockCount = project.blockCount ? project.blockCount : 0,
        content = JSON.stringify(project),
        args = [projectName, createTime, createTime, blockCount, content, projectType, userId];
    pool.query(sql_createProject, args, (err, result) => {
        if (err) {
            ret = {
                result: -1,
                msg: "创建失败"
            }
            console.error(err);
        } else {
            var projId = result.insertId;
            ret = {
                result: 0,
                projId: projId,
                projectType: projectType
            }
            var base64Data = thumbnail.substr("data:image/jpeg;base64,".length);
            fs.writeFile(staticPath + "/static/project/" + projId + ".jpeg", base64Data, 'base64', (err2) => {
                console.error(err2);
            });
        }
        cb(ret);
    });
};

const updateProjById = (userId, project, thumbnail, cb) => {
    var projectName = project.projectName,
        blockCount = project.blockCount ? project.blockCount : 0,
        updateTime = moment().format('YYYY-MM-DD HH:mm:ss'),
        content = JSON.stringify(project),
        args = [projectName, updateTime, blockCount, content, project.id, userId];
    pool.query(sql_updateProjById, args, (err, result) => {
        if (!err && result.affectedRows < 1) {
            var ret = {
                result: -1,
                msg: "工程不存在"
            };
            cb(ret);
        } else {
            ret = {
                result: 0,
                msg: "更新成功"
            };
            console.error(err);
            cb(ret);
            if (!err) {
                var base64Data = thumbnail.substr("data:image/jpeg;base64,".length);
                fs.writeFile(staticPath + "/static/project/" + project.id + ".jpeg", base64Data, 'base64', (err2) => {
                    console.error(err2);
                });
            }
        }
    });
};

const updateVisitNum = (proId, userId) => {
    pool.query(sql_updateVisitNum, [proId, userId], (err) => {
        console.error(err);
    });
};

const removeProjById = (id, userId, cb) => {
    pool.query(sql_removeProjById, [id, userId], (error, result) => {
        if (error) {
            cb(error);
            return;
        }
        if (result.affectedRows === 1) {
            cb();
            var path = staticPath + "/static/project/" + id + ".jpeg";
            if (fs.existsSync(path)) {
                fs.unlinkSync(path);
            }
        } else {
            var ret = {
                result: -1,
                msg: "工程不存在"
            };
            cb(ret);
        }
    });
};
//获取用户工程列表
const getUserProjList = (userId, cb) => {
    var args = [userId];
    pool.query(sql_projectInfos, args, (err, rows) => {
        var projList = [];
        if (err) {
            console.error(err);
        } else {
            for (let key in rows) {
                var row = rows[key];
                var projectInfo = {
                    id: row.id,
                    name: row.name,
                    createTime: row.createTime,
                    updateTime: row.updateTime,
                    blockCount: row.blockCount,
                    visited: row.visited,
                    length: row.length
                }
                projList.push(projectInfo);
            }
        }
        cb(projList);
    });
};

const projectCount = (userId, cb) => {
    var args = [userId];
    pool.query(sql_projectCount, args, (err, rows) => {
        if (err) {
            console.error(err);
            cb(0);
        } else {
            cb(rows[0].count);
        }
    });
};

//聚合用户查看个人作品列表（分页）
const getUserProjListByPage = (userId, offset, limit, cb) => {
    projectCount(userId, (count) => {
        var ret = {
            result: 0,
            totalNum: count,
            list: []
        };
        if (count === 0) {
            cb(ret);
        } else {
            offset = parseInt(offset),
                limit = parseInt(limit);
            var args = [userId, offset, limit];
            pool.query(sql_projectInfosByPage, args, (err, rows) => {
                if (err) {
                    console.error(err);
                } else {
                    var projList = [];
                    for (let key in rows) {
                        var row = rows[key],
                            projectInfo = {
                                id: row.id,
                                name: row.name,
                                projectType: row.projectType,
                                updateTime: row.updateTime
                            };
                        projList.push(projectInfo);
                    }
                    ret.list = projList;
                }
                cb(ret);
            });
        }
    });
};

const hasProject = (userId, projectId, cb) => {
    var args = [projectId, userId];
    pool.query(sql_hasProject, args, (err, rows) => {
        if (err) {
            console.error(err);
            // cb(err);
        } else {
            cb(rows[0].count > 0);
        }
    });
};

//判断是否存在已经分享过的工程
const hasProject_share = (userId, projectId, cb) => {
    var args = [userId, projectId];
    pool.query(sql_hasProject_share, args, (err, rows) => {
        if (err) {
            console.error(err);
            // cb(err);
        } else {
            cb(rows[0].count > 0);
        }
    });
};

//更新分享后的作品id为改编的作品id
const updatejuheSharedById = (userId, shareId, fromShareId, cb) => {
    var ret,
        args = [fromShareId, userId, shareId];
    pool.query(sql_updatejuheSharedById, args, (err, result) => {
        if (err) {
            console.error(err);
            ret = {
                result: -1,
                msg: "更新失败"
            }
        } else if (result.affectedRows < 1) {
            ret = {
                result: -1,
                msg: "工程不存在"
            }
        } else {
            ret = {
                result: 0,
                msg: "更新成功"
            }
        }
        cb(ret);
    });
}

const saveProj = (userId, content, thumbnail, cb) => {
    let ret,
        project = JSON.parse(content),
        createP = () => {
            userService.getUserPermission(userId, (permissionTypes) => {
                if (permissionTypes.indexOf("UNLIMIT_SPACE") > -1) {//有无限空间权限
                    createProject(userId, project, "normal", thumbnail, (rb) => {
                        if (rb.result == 0) {
                            ret = rb
                            cb(ret);
                        } else {
                            ret = {
                                result: -1,
                                msg: "保存工程出错"
                            };
                            cb(ret);
                        }
                    });
                } else {
                    projectCount(userId, (pCount) => {
                        userService.getUserLimit(userId, (limitNum) => {
                            if (pCount >= limitNum) {
                                ret = {
                                    result: -2,
                                    msg: "工程数量已达上限"
                                };
                                cb(ret);
                            } else {
                                createProject(userId, project, "normal", thumbnail, (rb) => {
                                    if (rb.result == 0) {
                                        ret = rb
                                        cb(ret);
                                    } else {
                                        ret = {
                                            result: -1,
                                            msg: "保存工程出错"
                                        };
                                        cb(ret);
                                    }
                                });
                            }
                        });
                    });
                }
            });
        };

    if (project.id) {
        hasProject(userId, project.id, (has) => {
            if (has) {
                updateProjById(userId, project, thumbnail, (rb1) => {
                    if (rb1.result == 0) {
                        ret = {
                            result: 0,
                            projId: project.id
                        };
                        cb(ret);

                    } else {
                        ret = {
                            result: -2,
                            msg: "保存工程出错"
                        };
                        cb(ret);
                        console.error(err);
                    }
                });
            } else {
                createP();
                console.log("does not have an project.id , create new project.")
            }

        });
    } else {
        console.log("does not have an id , create new project.");
        createP();
    }
}

//根据用户id和工程id获取用户工程信息
const getProjById = (userId, projId, cb) => {
    var args = [userId, projId];
    pool.query(sql_getProjById, args, (err, rows) => {
        var ret;
        if (err) {
            console.error(err);
            ret = {
                result: -1,
                msg: "获取项目出错，请稍后再试！"
            }
        } else if (rows.length === 0) {
            ret = {
                result: -1,
                msg: "获取项目出错，项目不存在！"
            }
        } else {
            ret = {
                result: 0,
                name: rows[0].name,
                content: rows[0].content
            }
        }
        cb(ret);
    });
};

//创建更新聚合分享的图片
const copyProjImgToShare = (projId, shareId) => {
    var from = staticPath + "/static/project/" + projId + ".jpeg",
        to = staticPath + "/static/juheshare/" + shareId + ".jpeg";
    fs.readFile(from, (err, data) => {
        if (err) {
            console.error(err);
        } else {
            fs.writeFile(to, data, (err) => {
                if (err) {
                    console.error(err);
                }
            });
        }
    });
};

const createShare = (userId, projId, content, cb) => {
    var ret;
    content = JSON.parse(content);
    delete content.id;
    var projectName = content.projectName,
        shareId = content.shareId ? content.shareId : -1, //分享的工程的之前的分享id
        content = JSON.stringify(content),
        args = [userId, projId, projectName, content];
    pool.query(sql_juheShareProj_create, args, (err, result) => {
        if (err) {
            ret = {
                result: -1,
                msg: "分享失败"
            };
            console.error(err);
            cb(ret);
        } else {
            var shareId = result.insertId;
            copyProjImgToShare(projId, shareId);
            ret = {
                result: 0,
                projId: shareId,
                // msg: "分享成功"
            };
            cb(ret);
        }

    });
};

//聚合平台分享和更新分享	
const juheShareProj = (userId, projId, cb) => {
    var ret;
    getProjById(userId, projId, (list) => {
        if (list.result === 0) {
            var content = JSON.parse(list.content);
            createShare(userId, projId, list.content, (rb) => {
                if (rb.result === 0) {
                    var shareId = rb.projId,
                        fromShareId = content.jhShareId;
                    //					console.log(typeof content + "*****" + fromShareId + "***" + shareId);
                    if (fromShareId) {
                        updatejuheSharedById(userId, shareId, fromShareId, (rb) => {
                            if (rb.result === -1) {
                                ret = {
                                    result: -1,
                                    msg: "分享失败"
                                }
                                cb(ret);
                            } else {
                                ret = {
                                    result: 0,
                                    shareId: shareId,
                                    fromShareId: fromShareId
                                }
                                cb(ret);
                            }
                        });

                    } else {
                        updateContestRecordPublishFlag(userId, projId); //仅供科技日报的创造大赛用,更新科技日报参赛记录
                        ret = {
                            result: 0,
                            shareId: shareId
                        }
                        cb(ret);
                    }
                } else {
                    ret = {
                        result: -1,
                        msg: "分享失败"
                    };
                    cb(ret);
                }

            });
        } else {
            ret = {
                result: -1,
                msg: "分享失败"
            };
            cb(ret);
        }

    });
};
//小组发帖分享
const juheGroupShareProj = (userId, projId, cb) => {
    const copyProjImgToGroup = (projId, id) => {
        var from = staticPath + "/static/project/" + projId + ".jpeg",
            to = staticPath + "/static/juhegroup/" + id + ".jpeg";
        fs.readFile(from, (err, data) => {
            if (err) {
                console.error(err);
            } else {
                fs.writeFile(to, data, (err) => {
                    if (err) {
                        console.error(err);
                    }
                });
            }
        });
    },
        createGroupShare = (content) => {
            content = JSON.parse(content);
            var projectName = content.projectName;
            delete content.id;
            content = JSON.stringify(content);
            var args = [userId, projectName, content];
            pool.query(sql_groupShare_create, args, (err, result) => {
                if (err) {
                    ret = {
                        result: -1,
                        msg: "小组分享失败"
                    };
                    console.error(err);
                } else {
                    var id = result.insertId;
                    copyProjImgToGroup(projId, id);
                    ret = {
                        result: 0,
                        id: id
                    };
                }
                cb(ret);
            });
        };
    getProjById(userId, projId, (ret) => {
        if (ret.result === 0) {
            createGroupShare(ret.content);
        } else {
            var ret = {
                result: -1,
                msg: "小组分享失败"
            };
            cb(ret);
        }
    });
}

//取消分享的工程
const cancleShareProj = (userId, projId, cb) => {
    var args = [userId, projId];
    pool.query(sql_cancleShareProj, args, (err) => {
        if (err) {
            ret = {
                result: -1,
                msg: "取消分享失败"
            };
        } else {
            ret = {
                result: 0,
                msg: "取消分享成功"
            };
        }
        cb(ret);
    });
}

//查看聚合小组分享的工程
const viewJuheGroupShareProjByPid = (projId, cb) => {
    var args = [projId];
    pool.query(sql_viewJuheGroupShareProjByPid, args, (err, rows) => {
        var ret;
        if (err) {
            console.error(err);
            ret = {
                result: -1,
                msg: "获取分享出错，请稍后再试！"
            }
        } else if (rows.length === 0) {
            ret = {
                result: -1,
                msg: "获取项目出错，分享不存在！"
            }
        } else {
            ret = {
                result: 0,
                content: rows[0].content
            }
        }
        cb(ret);
    });
};

//更新源文件
const updateShareSource = (userId, projInfo, cb) => {
    var ret,
        shareId = projInfo.shareId,
        projId = projInfo.projId;
    getProjById(userId, projId, (list) => {
        //			console.log(userId)
        var name = list.name,
            content = list.content,
            args = [name, content, userId, shareId];
        pool.query(sql_shareProj_update, args, (err) => {
            if (err) {
                console.error(err);
                ret = {
                    result: -1,
                    msg: "更新源文件失败"
                }
            } else {
                copyProjImgToShare(projId, shareId);
                ret = {
                    result: 0,
                    msg: "更新源文件成功"
                }
            }
            cb(ret);
        });
    });

}

//查看分享的工程  
const viewShareProjByPid = (shareId, cb) => {
    var args = [shareId];
    pool.query(sql_viewShareProjByPid, args, (err, rows) => {
        var ret;
        if (err) {
            console.error(err);
            ret = {
                result: -1,
                msg: "获取分享出错，请稍后再试！"
            }
        } else if (rows.length === 0) {
            ret = {
                result: -1,
                msg: "获取项目出错，分享不存在！"
            }
        } else {
            ret = {
                result: 0,
                content: rows[0].content
            }
        }
        cb(ret);
    });
};

const juheShareProjectCount = (userId, cb) => {
    var args = [userId];
    pool.query(sql_juheShareProjectCount, args, (err, rows) => {
        if (err) {
            console.error(err);
            cb(0);
        } else {
            cb(rows[0].count);
        }
    });
};
//聚合分享每个作品的历史记录数量
const juheShareHistoryProjectCount = (userId, projId, cb) => {
    var args = [userId, projId];
    pool.query(sql_juheShareHistoryProjectCount, args, (err, rows) => {
        if (err) {
            console.error(err);
            cb(0);
        } else {
            cb(rows[0].count);
        }
    });
};

//聚合分享每个作品改编作品的数量
const juheShareAdaptProjectCount = (userId, fromShareId, cb) => {
    var args = [userId, fromShareId];
    pool.query(sql_juheShareAdaptProjectCount, args, (err, rows) => {
        if (err) {
            console.error(err);
            cb(0);
        } else {
            cb(rows[0].count);
        }
    });
};

//查询最新的分享id
const getMaxShareId = (userId, projId, cb) => {
    var ret, args = [userId, projId];
    pool.query(sql_getMaxShareId, args, (err, rows) => {
        if (err) {
            console.error(err);
            ret = {
                result: -1,
                msg: "获取失败"
            }
        } else {
            ret = {
                result: 0,
                maxId: rows[0].maxId
            }
        }
        cb(ret);
    });
}

//聚合用户查看个人分享作品列表(分页)
const getJuheShareProListjByPage = (userId, offset, limit, cb) => {
    juheShareProjectCount(userId, (count) => {
        var ret = {
            result: 0,
            totalNum: count
        };
        if (count === 0) {
            ret.list = [];
            cb(ret);
        } else {
            offset = parseInt(offset),
                limit = parseInt(limit);
            var args = [userId, userId, offset, limit];
            pool.query(sql_getJuheShareProListjByPage, args, (err, rows) => {
                if (err) {
                    console.error(err);
                    ret.list = [];
                } else {
                    var projList = [];
                    for (var key in rows) {
                        var row = rows[key];
                        var projectInfo = {
                            id: row.id,
                            name: row.name,
                            updateTime: row.createTime
                        }
                        projList.push(projectInfo);
                    }
                    ret.list = projList;
                }
                cb(ret);
            });
        }
    });
};

//聚合用户查看个人分享作品历史列表（分页）
const listJuheShareHistoryProjByPage = (userId, projId, offset, limit, cb) => {
    juheShareHistoryProjectCount(userId, projId, (count) => {
        var ret = {
            result: 0,
            totalNum: count
        };
        if (count === 0) {
            ret.list = [];
            cb(ret);
        } else {
            offset = parseInt(offset),
                limit = parseInt(limit);
            var args = [userId, projId, offset, limit];
            pool.query(sql_getJuheShareHistoryProjListByPage, args, (err, rows) => {
                if (err) {
                    console.error(err);
                    ret.list = [];
                } else {
                    getMaxShareId(userId, projId, (rb) => {
                        //						console.log(rb.maxId);
                        if (rb.result === 0) {
                            var projList = [];
                            for (var key in rows) {
                                var row = rows[key];
                                if (row.id < rb.maxId) {
                                    var projectInfo = {
                                        id: row.id,
                                        name: row.name,
                                        createTime: row.createTime
                                    }
                                    projList.push(projectInfo);
                                }

                            }
                            ret.list = projList;
                            cb(ret);
                        }
                    });

                }

            });
        }
    });
};

//聚合用户查看个人分享作品后改编的作品列表(分页)
const getJuheShareAdaptListByPage = (userId, fromShareId, offset, limit, cb) => {
    juheShareAdaptProjectCount(userId, fromShareId, (count) => {
        let ret = {
            result: 0,
            totalNum: count
        };
        if (count === 0) {
            ret.list = [];
            cb(ret);
        } else {
            offset = parseInt(offset),
                limit = parseInt(limit);
            let args = [userId, fromShareId, offset, limit];
            pool.query(sql_getJuheShareAdaptListByPage, args, (err, rows) => {
                if (err) {
                    console.error(err);
                    ret.list = [];
                } else {
                    let projList = [];
                    for (let key in rows) {
                        let row = rows[key];
                        let projectInfo = {
                            id: row.id,
                            name: row.name,
                            createTime: row.createTime
                        }
                        projList.push(projectInfo);
                    }
                    ret.list = projList;
                }
                cb(ret);
            });
        }
    });
}

//根据用户id和工程id获取用户工程信息
const getUserProjByPid = (projId, cb) => {
    let args = [projId];
    pool.query(sql_getUserProjByPid, args, (err, rows) => {
        let ret;
        if (err) {
            console.error(err);
            ret = {
                result: -1,
                msg: "获取项目出错，请稍后再试！"
            }
        } else if (rows.length === 0) {
            ret = {
                result: -1,
                msg: "获取项目出错，项目不存在！"
            }
        } else {
            ret = {
                result: 0,
                content: rows[0].content
            }
        }
        cb(ret);
    });
};

module.exports = {
    addProjTemplete,
    updateProjById,
    removeProjById,
    getUserProjList,
    getUserProjListByPage,
    saveProj,
    getProjById,
    getUserProjByPid,
    updateVisitNum,
    juheShareProj,
    juheGroupShareProj,
    cancleShareProj,
    updateShareSource,
    viewShareProjByPid,
    viewJuheGroupShareProjByPid,
    listJuheShareHistoryProjByPage,
    getJuheShareAdaptListByPage,
    updateProject_tmp,
    getJuheShareProListjByPage
};